//
//  EditUUIDViewController.swift
//  MTBLETools
//
//  Created by 方强 on 16/11/28.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit

class EditUUIDViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    static func getActivity() -> EditUUIDViewController{
        let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main);
        let vc = storyBoard.instantiateViewController(withIdentifier: "EditUUIDViewController") as! EditUUIDViewController;
        
        return vc;
    }

    private var mStaticDatas:StaticDatas!;
    override func viewDidLoad() {
        super.viewDidLoad()
        mStaticDatas = StaticDatas.getInstance();
        
        initView();
        // Do any additional setup after loading the view.
        
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(keyboardHide));
        tapGestureRecognizer.cancelsTouchesInView = false;
        self.view.addGestureRecognizer(tapGestureRecognizer);
    }
    
    func keyboardHide(tap:UITapGestureRecognizer){
        self.view.endEditing(true);
    }
    
    // 初始化控件
    @IBOutlet weak var uuid_listView: UITableView!
    @IBOutlet weak var name_edit: UITextField!
    @IBOutlet weak var uuid_edit: UITextField!
    private func initView(){
        uuid_listView.dataSource = self;
        uuid_listView.delegate = self;
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return mStaticDatas.uuidList.count;
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let obj: AnyObject? = tableView.dequeueReusableCell(withIdentifier: "UUIDCell");
        var cell: UUIDCell!;
        if(obj == nil){
            cell = UUIDCell.getCell();
        }else{
            cell = obj as! UUIDCell;
        }
        
        cell.refreshDis(value: mStaticDatas.uuidList[indexPath.row]);
        
        return cell;
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 50;
    }
    
    private var selectIndex = -1;
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
        print("tableView->\(indexPath.row)");
        
        self.selectIndex = indexPath.row;
        
        name_edit.text = mStaticDatas.uuidList[selectIndex].getName();
        uuid_edit.text = mStaticDatas.uuidList[selectIndex].getUuid();
        
        name_edit.isEnabled = true;
        uuid_edit.isEnabled = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func navOnclickAciton(_ sender: UIBarButtonItem) {
        if(sender.tag == 1){  // 返回
            self.dismiss(animated: false, completion: { 
                
            });
            return;
        }
        if(sender.tag == 2){  // 添加新UUID
            
            let newuuid = UuidAndName(name: "未命名", uuid: "FDA50693-A4E2-4FB1-AFCF-C6EB07647825");
            newuuid.setId(id: UuidAndName.add(database: mStaticDatas.db, device: newuuid));
            mStaticDatas.uuidList.append(newuuid);
            
            uuid_listView.reloadData();
            
            uuid_listView.selectRow(at: IndexPath(row: mStaticDatas.uuidList.count-1, section: 0), animated: false, scrollPosition: UITableViewScrollPosition.none);
            self.tableView(uuid_listView, didSelectRowAt: IndexPath(row: mStaticDatas.uuidList.count-1, section: 0));
            
            return;
        }
    }
    @IBAction func OnclickAction(_ sender: UIButton) {
        if(sender.tag == 1){  // 删除
            
            if(selectIndex == -1){
                return;
            }
            
            UuidAndName.delete(database: mStaticDatas.db, device: mStaticDatas.uuidList[selectIndex]);
            
            mStaticDatas.uuidList.remove(at: selectIndex);
            
            uuid_listView.reloadData();
            
            selectIndex = -1;
            
            return;
        }
        if(sender.tag == 2){  // 确定
            
            if(selectIndex == -1){
                return;
            }
            
            if((name_edit.text == nil) || (name_edit.text?.lengthOfBytes(using: String.Encoding.utf8) == 0)){
                showFailAlert(erromsg: "请输入名字");
                return;
            }
            
            if((uuid_edit.text == nil) || (uuid_edit.text?.lengthOfBytes(using: String.Encoding.utf8) != 36)){
                showFailAlert(erromsg: "UUID格式不对");
                return;
            }
            
            let uuid_byte = uuid_edit.text!.data(using: String.Encoding.utf8)!;
            if((uuid_byte[8] != 0x2D) || (uuid_byte[13] != 0x2D) || (uuid_byte[18] != 0x2D) || (uuid_byte[23] != 0x2D)){
                showFailAlert(erromsg: "UUID格式不对");
                return;
            }
            
            mStaticDatas.uuidList[selectIndex].setName(name: name_edit.text!);
            mStaticDatas.uuidList[selectIndex].setUuid(uuid: uuid_edit.text!);
            
            UuidAndName.updata(database: mStaticDatas.db, device: mStaticDatas.uuidList[selectIndex]);
            
            uuid_listView.reloadData();
            
            return;
        }
    }
    
    // 显示失败对话框
    private var baseAlert:UIAlertView!;
    private func showFailAlert(erromsg: String){
        baseAlert = UIAlertView(title: "Fail", message: erromsg, delegate: nil, cancelButtonTitle: "OK");
        baseAlert.show();
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    @IBAction func TextFinish(_ sender: UITextField) {
        sender.resignFirstResponder();
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        self.view.openKeyboardOffsetView();
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated);
        self.view.closeKeyboardOffsetView();
    }

}
